﻿"use strict";

// ----------------------------------
// Depends on:
//   jQuery
//   Microsoft.Ajax
// ----------------------------------

// ----------------------------------
// Guard.

if (typeof (Sys) == 'undefined') {
	alert('Micorsoft.Ajax has not been loaded.');
}

if (typeof (jQuery) == 'undefined') {
	alert('jQuery has not been loaded.');
}

// ----------------------------------
// Constants.

var my_overlayZIndex = 10998;

var my_topMessageZIndex = my_overlayZIndex + 5;

var my_updateMessageZIndex = my_overlayZIndex + 20;

var my_defaultUpdateMessage = 'Loading...';

// ----------------------------------
// Global variables.

var my_updateMessage = null;
var my_responseErrors = [];
var my_responseWarns = [];
var my_responseInformations = [];
var my_externalCallEntries = {};

var my_messageHandlers = new Object();

var my_defaultMessageHandler = function (errors, warns, infos) {
	var fun1 = function (s) { return s; }; // Mapping.
	var fun2 = function (s) { return s; }; // Filter.
	var fun3 = function (s, a) { return s + '\r\n' + a }; // Join.

	var errorsMsg = my_reduce(my_map(errors, fun1, fun2), fun3, '');
	if (errorsMsg) {
		alert(errorsMsg);
		return;
	}

	var warnsMsg = my_reduce(my_map(warns, fun1, fun2), fun3, '');
	if (warnsMsg) {
		alert(warnsMsg);
		return;
	}

	var infosMsg = my_reduce(my_map(infos, fun1, fun2), fun3, '');
	if (infosMsg) {
		alert(infosMsg);
		return;
	}
}

my_messageHandlers['default'] = my_defaultMessageHandler;

// ----------------------------------
// Global functions.

if (typeof String.prototype.endsWith !== 'function') {
	String.prototype.endsWith = function (suffix) {
		return this.indexOf(suffix, this.length - suffix.length) !== -1;
	};
}

/**
* GridView button column
* @param name name of group checkbox.
*/
function groupCheckBoxes(name) {
	if (!name)
		return;

	var trigger = jQuery("input:checkbox[name=" + name + "]");

	var group = name.substring(0, name.length - 4); // remove suffix '_all'.

	var checked = trigger.prop("checked");
	jQuery("input:checkbox:enabled[name=" + group + "]").prop("checked", checked);

	return true;
}

/**
* Set value of URL parameter.
* @param pn name of parameter.
* @param pv new value of parameter.
*/
function setURLParam(pn, pv) {
	var pp = purl().params();
	pp[pn] = pv;

	window.location.href = window.location.protocol + window.location.host + window.location.pathname + "?" + jQuery.param(pp);

	return false;
}

/**
*
* @param o
* @param f1
* @param f2
*/
function my_map(o, f1, f2) {
	var ret = [];

	if (!o) {
		return ret;
	}

	for (var key in o) {
		var oo = o[key];
		if (f2 && !f2(oo))
			continue;

		ret.push(f1(oo));
	}

	return ret;
}

/**
*
* @param o
* @param f1
* @param init
*/
function my_reduce(o, f1, init) {
	if (!o) {
		return init;
	}

	for (var key in o) {
		var oo = o[key];
		if (!init) {
			init = oo;
		} else {
			init = f1(init, oo);
		}
	}

	return init;
}

/**
*
*/
function my_addBookmark() {
	if (window.sidebar) {
		// Mozilla Firefox Bookmark
		window.sidebar.addPanel(document.title, location.href, '');
	} else if (document.all) {
		// IE Favorite
		window.external.AddFavorite(location.href, document.title);
	} else {
		window.alert('Not supported.');
	}

	return false;
}

/**
*
*/
function my_setHomepage() {
	if (document.all) {
		document.body.style.behavior = 'url(#default#homepage)';
		document.body.setHomePage(location.href);
	} else {
		window.alert('Not supported.');
	}

	return false;
}

/**
*
*/
function my_registerExternalCallEntry(callEntry, callFunction) {
	my_externalCallEntries[callEntry] = callFunction;
}

/**
*
*/
function my_callExternalEntry(callEntry) {
	var c = my_externalCallEntries[callEntry];
	if (c) {
		c.call(this);
	}
}

/**
*
*/
function my_closeAndCallOpener(arg) {
	darg = {};
	arg = jQuery.extend({ callEntry: '' }, darg, arg);

	if (window.opener && !window.opener.closed) {
		try {
			if (arg.callEntry) {
				window.opener.my_callExternalEntry(arg.callEntry);
			}
		} catch (calle) {
		}
	}

	window.opener = null;
	window.close();
}

/**
*
*
*/
function myManageFiles_addFile(cntId) {
	var cnt = jQuery("#" + cntId);

	var lastItem = jQuery("li:has(input:file):last", cnt);
	var newItem = lastItem.clone();

	var newFile = jQuery(":file", newItem);

	var seq = (parseInt(newItem.attr("seq")) + 1).toString();
	newItem.attr("seq", seq);
	newFile.attr("seq", seq);

	var name = newFile.prop("name");
	var l = name.lastIndexOf("_");
	newFile.prop("name", name.substring(0, l) + "_" + seq);

	var newDeleteNewButton = jQuery("input:image", newItem);
	newDeleteNewButton.attr("onclick", "return myManageFiles_deleteNewFile('" + cntId + "', " + seq + ");")

	newItem.insertAfter(lastItem);

	return false;
}

/**
*
*
*/
function myManageFiles_checkFile(cntId, seq) {
	var cnt = jQuery("#" + cntId);

	var cItem = jQuery("li[seq=" + seq + "]", cnt);

	var cbx = jQuery("input:checkbox:first", cItem);
	var lnk = jQuery("a:first", cItem);
	var ibt1 = jQuery(".deleteFile", cItem);
	var ibt2 = jQuery(".recoverFile", cItem);

	cbx.prop("checked", true);
	ibt1.hide();
	ibt2.show();

	lnk.addClass("removedFile");

	return false;
}

/**
*
*
*/
function myManageFiles_uncheckFile(cntId, seq) {
	var cnt = jQuery("#" + cntId);

	var cItem = jQuery("li[seq=" + seq + "]", cnt);

	var cbx = jQuery("input:checkbox:first", cItem);
	var lnk = jQuery("a:first", cItem);
	var ibt1 = jQuery(".deleteFile", cItem);
	var ibt2 = jQuery(".recoverFile", cItem);

	cbx.prop("checked", false);
	ibt2.hide();
	ibt1.show();

	lnk.removeClass("removedFile");

	return false;
}

/**
*
*
*/
function myManageFiles_deleteNewFile(cntId, seq) {
	var cnt = jQuery("#" + cntId);

	var cItem = jQuery("li[seq=" + seq + "]", cnt);

	var ef = jQuery(":file:enabled", cnt);
	if (ef.size() <= 1) {
		// Cannot delete the unique file.
		return false;
	}

	cItem.remove().empty();

	return false;
}

/**
* 
*
*/
function my_htmlEncode(s) {
	if (!s)
		return '';

	s = s.replace(/&/g, "&gt;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/ /g, "&nbsp;")
		.replace(/\'/g, "&#39;")
		.replace(/\"/g, "&quot;")
		.replace(/\n/g, "<br>");

	return s;
}

/**
*
*
*/
function myViewFiles_previewTxtFile(cntId, url, title, title2) {
	var cnt = jQuery('#' + cntId);

	var previewBox = jQuery('<div class="myViewFiles_previewTxtBox" style="display:none;" ></div>');

	var previewBoxContent = jQuery('<div class="myViewFiles_previewContentLoading" style="overflow:auto;text-align:center;" ></div>');

	var titleBar = jQuery('<div class="myViewFiles_previewTitleBar" ></div>');
	var titleText = jQuery('<span class="myViewFiles_previewTitleText" ></span>');
	titleText.text(title2);
	titleText.prop("title", title);

	var closeBtn = jQuery('<span class="myViewFiles_previewTitleClose"></span>');

	var npre = null;

	titleBar.append(titleText);
	titleBar.append(closeBtn);
	// Since npre is null yet, it should not be append to previewBoxContent.
	previewBox.append(titleBar);
	previewBox.append(previewBoxContent);
	jQuery("body").append(previewBox);

	my_showOverlay();

	var sw = document.documentElement.scrollWidth || document.body.scrollWidth;
	var sh = document.documentElement.scrollHeight || document.body.scrollHeight;
	var cw = document.documentElement.clientWidth || document.body.clientWidth;
	var ch = document.documentElement.clientHeight || document.body.clientHeight;
	var st = document.documentElement.scrollTop || document.body.scrollTop;

	var mw = cw * .8;
	var mh = ch * .8;
	var ml = (sw - mw) / 2; // left
	var mt = st + (ch - mh) / 2;  // top

	var contentPadding = 4;
	previewBoxContent.css('position', 'absolute');
	previewBoxContent.css('width', (mw - 2 * contentPadding) + 'px');
	previewBoxContent.css('height', (mh - 2 * contentPadding - titleBar.height()) + 'px');
	previewBoxContent.css('left', contentPadding + 'px');
	previewBoxContent.css('top', (contentPadding + titleBar.height()) + 'px');

	previewBox.css('position', 'absolute');
	previewBox.css('z-index', my_overlayZIndex + 5);
	previewBox.css('width', mw + 'px');
	previewBox.css('height', mh + 'px');
	previewBox.css('left', ml + 'px');
	previewBox.css('top', mt + 'px');
	previewBox.show();

	jQuery.ajax({
		url: url,
		type: 'POST',
		data: { timestamp: new Date().getTime() },
		dataType: 'text'
	}).done(function (responseText) {
		npre = jQuery('<PRE style="display:none;" >\n\n' + my_htmlEncode(responseText) + '</PRE>');
		npre.appendTo(previewBoxContent);

		previewBoxContent.removeClass("myViewFiles_previewContentLoading");
		previewBoxContent.addClass("myViewFiles_previewContentLoaded");

		npre.show();
	});

	closeBtn.click(function () {
		if (npre) {
			npre.html('');
			npre.remove().empty();
		}

		previewBox.hide(0, function () {
			previewBox.remove().empty();
			previewBox = null;

			my_hideOverlay();
		});
	});

	return false;
}

/**
*
*
*/
function myViewFiles_previewImgFile(cntId, url, title, title2) {
	var cnt = jQuery('#' + cntId);

	var previewBox = jQuery('<div class="myViewFiles_previewImgBox" style="display:none;" ></div>');

	var previewBoxContent = jQuery('<div class="myViewFiles_previewContentLoading" style="overflow:auto;text-align:center;" ></div>');

	var titleBar = jQuery('<div class="myViewFiles_previewTitleBar" ></div>');
	var titleText = jQuery('<span class="myViewFiles_previewTitleText" ></span>');
	titleText.text(title2);
	titleText.prop("title", title);

	var closeBtn = jQuery('<span class="myViewFiles_previewTitleClose"></span>');

	var img = jQuery('<img style="display:none;" />');

	titleBar.append(titleText);
	titleBar.append(closeBtn);
	previewBoxContent.append(img);
	previewBox.append(titleBar);
	previewBox.append(previewBoxContent);
	jQuery("body").append(previewBox);

	my_showOverlay();

	var contentPadding = 4;
	var sw = document.documentElement.scrollWidth || document.body.scrollWidth;
	var sh = document.documentElement.scrollHeight || document.body.scrollHeight;
	var cw = document.documentElement.clientWidth || document.body.clientWidth;
	var ch = document.documentElement.clientHeight || document.body.clientHeight;
	var st = document.documentElement.scrollTop || document.body.scrollTop;

	var mw = cw * .8;
	var mh = ch * .8;
	var ml = (sw - mw) / 2; // left
	var mt = st + (ch - mh) / 2;  // top

	previewBoxContent.css('position', 'absolute');
	previewBoxContent.css('width', (mw - 2 * contentPadding) + 'px');
	previewBoxContent.css('height', (mh - 2 * contentPadding - titleBar.height()) + 'px');
	previewBoxContent.css('left', contentPadding + 'px');
	previewBoxContent.css('top', (contentPadding + titleBar.height()) + 'px');

	previewBox.css('position', 'absolute');
	previewBox.css('z-index', my_overlayZIndex + 5);
	previewBox.css('width', mw + 'px');
	previewBox.css('height', mh + 'px');
	previewBox.css('left', ml + 'px');
	previewBox.css('top', mt + 'px');
	previewBox.show();

	img.prop('src', url).load(function () {
		if (img.height() < previewBoxContent.height()) {
			var imt = (previewBoxContent.height() - img.height()) / 2;
			img.css('margin-top', imt + 'px');
		} else {
			img.css('margin-top', '0');
		}

		previewBoxContent.removeClass("myViewFiles_previewContentLoading");
		previewBoxContent.addClass("myViewFiles_previewContentLoaded");

		img.show();
	});

	closeBtn.click(function () {
		img.prop('src', '');
		img.remove().empty();

		previewBox.hide(0, function () {
			previewBox.remove().empty();
			previewBox = null;

			my_hideOverlay();
		});
	});

	return false;
}

/**
*
*
*/
function my_hideMe(obj, settings) {
	settings = jQuery.extend({ speed: 'normal', callback: null }, settings);

	var me = jQuery(obj);

	me.fadeOut(settings.speed, settings.callback);

	return false;
}

/**
* Validate date.
* @param source Validator.
& @param args
*/
function my_dateTimeValidatorEvaluateIsValid1(source, args) {
	var value = args.Value;
	if (!value) {
		args.IsValid = true;
		return;
	}

	var rx = /^\s*(\d\d\d\d)\s*\-\s*((0|1)?\d)(\s*\-\s*((0|1|2|3)?\d))?\s*$/i;
	var matches = rx.exec(jQuery.trim(value));
	if (matches == null || value != matches[0]) {
		args.IsValid = false;
		return;
	}

	try {
		var y = parseInt(matches[1]);
		var m = parseInt(matches[2] || '1') - 1;
		var d = parseInt(matches[5] || '1');
		var d1 = new Date(y, m, d);

		args.IsValid = d1.getFullYear() == y && d1.getMonth() == m && d1.getDate() == d;
	} catch (err) {
		args.IsValid = false;
	}
}

/**
* Validate date & time.
* @param val Validator.
*/
function my_dateTimeValidatorEvaluateIsValid2(source, args) {
	var value = args.Value;
	if (!value) {
		args.IsValid = true;
		return;
	}

	var rx = /^\s*(\d\d\d\d)\s*\-\s*((0|1)?\d)(\s*\-\s*((0|1|2|3)?\d))?\s+(((0|1|2)?\d)\s*:\s*((0|1|2|3|4|5)?\d))?\s*$/i;
	var matches = rx.exec(jQuery.trim(value));
	if (matches == null || value != matches[0]) {
		args.IsValid = false;
		return;
	}

	try {
		var hh = parseInt(matches[8] || '0');
		var mm = parseInt(matches[10] || '0');

		if (hh < 0 || hh > 23 || mm < 0 || mm > 59) {
			return false;
		}

		var y = parseInt(matches[1]);
		var m = parseInt(matches[2] || '1') - 1;
		var d = parseInt(matches[5] || '1');
		var d1 = new Date(y, m, d);

		args.IsValid = d1.getFullYear() == y && d1.getMonth() == m && d1.getDate() == d;
	} catch (err) {
		args.Isvalid = true;
	}
}

/**
* Validate time.
* @param val Validator.
*/
function my_dateTimeValidatorEvaluateIsValid3(source, args) {
	var value = args.Value;
	if (!value) {
		args.IsValid = true;
		return;
	}

	var rx = /^\s*((0|1|2)?\d)\s*:\s*((0|1|2|3|4|5)?\d)\s*$/i;
	var matches = rx.exec(jQuery.trim(value));
	if (matches == null || value != matches[0]) {
		args.IsValid = false;
		return;
	}

	try {
		var hh = parseInt(matches[8] || '0');
		var mm = parseInt(matches[10] || '0');

		if (hh < 0 || hh > 23 || mm < 0 || mm > 59) {
			args.IsValid = false;
			return;
		}

		args.IsValid = true;
	} catch (err) {
		args.IsValid = false;
	}
}

/**
*
* @param msg
*/
function my_setUpdateMessage(msg) {
	my_updateMessage = msg;
}

/**
*
*
*/
function my_showOverlay() {
	var sw = document.documentElement.scrollWidth || document.body.scrollWidth;
	var sh = document.documentElement.scrollHeight || document.body.scrollHeight;

	var ol = jQuery('<div></div>');
	jQuery(document.body).prepend(ol);

	ol.addClass('my_overlay');
	ol.html('&nbsp;');
	ol.css('position', 'absolute');
	ol.css('z-index', my_overlayZIndex);
	ol.css('left', '0px');
	ol.css('top', '0px')
	ol.width(sw);
	ol.height(sh);
}

/**
*
*
*/
function my_showUpdateMessage() {
	var sw = document.documentElement.clientWidth || document.body.clientWidth;
	var st = document.documentElement.scrollTop || document.body.scrollTop;

	var msg = jQuery('<div class="my_updateMessage"></div>');
	jQuery(document.body).prepend(msg);

	msg.html(my_updateMessage || my_defaultUpdateMessage);
	msg.css('position', 'absolute');
	msg.css('z-index', my_updateMessageZIndex);
	var ml = msg.width();
	var mt = msg.offset().top;
	msg.offset({ left: (sw - ml) / 2, top: mt + st });
}

/**
*
*/
function my_hideOverlay() {
	var ol = jQuery("div.my_overlay");
	ol.hide(0, function () {
		ol.remove().empty();
	});
}

/**
*
*/
function my_hideUpdateMessage() {
	var msg = jQuery('div.my_updateMessage');
	msg.hide(0, function () {
		msg.remove().empty();
	});
}

function my_registerMessagesHandler(key, func) {
	Sys.Debug.assert(!!key, 'Parameter "key" cannot be null or empty!');

	Sys.Debug.assert(!!func, 'Parameter "func" cannot be null or empty!');

	Sys.Debug.assert(typeof func == 'function', 'Expected parameter "func" be a function, but was ' + typeof (func) + ' .');

	my_messageHandlers[key] = func;
}

function my_unregisterMessageHandler(key) {
	delete my_messageHandlers[key];
}

function my_clearMessageHandler() {
	my_messageHandlers = new Object();
}

function my_handleMessages() {
	if (my_messageHandlers) {
		for (var key in my_messageHandlers) {
			var func = my_messageHandlers[key];

			if (typeof (func) !== "function") {
				continue;
			}

			Sys.Debug.trace('Run message handler "' + key + '".');

			func.call(document, my_responseErrors, my_responseWarns, my_responseInformations);
		}
	}
}

//function my_registerDefaultButton(bid) {
//	var bt = document.getElementById("__formDefaultButtonTrigger");
//	var tt = document.getElementById(bid);
//	if (bt) {
//		if (tt) {
//			bt.onclick = function () {
//				tt.click();
//				return false;
//			}
//		} else {
//			bt.onclick = function () {
//				return false;
//			};
//		}
//	};
//}

Sys.Application.add_init(function () {
	Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(function (sender, e) {
		// Post data to a iframe if the response is a file.
		var elem = e.get_postBackElement();
		if (elem && elem.id && elem.id.endsWith('DownloadableFile')) {
			//
		}
	});

	Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function (sender, e) {
		my_showOverlay();
		my_showUpdateMessage();
	});

	Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(function (sender, e) {
		my_hideUpdateMessage();
	});

	Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function (sender, e) {
		// my_handleMessages();
	});

	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, e) {
		my_hideUpdateMessage();
		my_hideOverlay();

		var err = e.get_error();
		if (err != null) {
			var errName = err.name; //err.get_name();

			if (err.message) {
				my_responseErrors = [err.message];
				my_handleMessages();
			}

			Sys.Debug.traceDump(err);

			e.set_errorHandled(true);
		}
	});
});

Sys.Application.notifyScriptLoaded();
